package com.ssyc.gsk_teacher.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PickChooseManager;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.adapter.UploadShowPicGvAdapter;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPicker;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnMultiCompressListener;
import okhttp3.Call;

/**
 * 教师端--教师上传视频
 * Created by Kevin on 2018/6/30
 */

public class TeacherUploadVidioActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    //返回键
    private ImageView ivBack;

    //提交
    private ImageView iv_conmit;

    //展示选择图片的GridView
    private MyGridView mgv;

    //图片适配器
    private UploadShowPicGvAdapter adapter;

    //填充适配器的图片地址
    private List<String> mPicPaths;

    //视频链接
    private EditText et_url;

    //视频名称
    private EditText et_name;

    //名称
    private String name;

    //链接
    private String url;

    //视频类型
    private String vidioType = "0";

    //晒课
    private ImageView iv_shaike;

    //评课
    private ImageView iv_pingke;

    private TextView tv_pingke;

    private TextView tv_shaike;


    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.teacher_activity_upload_vidio;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //设置展示图片的适配器
        initGv();
    }

    /**
     * 设置展示选择图片GridView
     */
    private void initGv() {
        mPicPaths = new ArrayList<>();
        adapter = new UploadShowPicGvAdapter(this, mPicPaths);
        mgv.setAdapter(adapter);
        mgv.setOnItemClickListener(this);

        iv_conmit.setOnClickListener(this);
    }


    /**
     * 初始化视图的方法
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        mgv = findViewById(R.id.mgv);
        iv_conmit = findView(R.id.iv_conmit);
        et_name = findView(R.id.et_name);
        et_url = findView(R.id.et_url);
        iv_shaike = findView(R.id.iv_shaike);
        iv_pingke = findView(R.id.iv_pingke);
        tv_shaike = findView(R.id.tv_shaike);
        tv_pingke = findView(R.id.tv_pingke);

        iv_pingke.setOnClickListener(this);
        iv_shaike.setOnClickListener(this);
        tv_shaike.setOnClickListener(this);
        tv_pingke.setOnClickListener(this);
    }

    /**
     * 先判断添加的内容的完整性
     * 然后做图片上传的操作
     */
    private void doUploading() {
        name = et_name.getText().toString();
        url = et_url.getText().toString();
        if (TextUtils.isEmpty(name)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请输入视频名称", 0).show();
            return;
        }

        if (TextUtils.isEmpty(url)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请输入视频链接", 0).show();
            return;
        }

        if (mPicPaths == null || mPicPaths.size() == 0) {
//            SnackbarUtil.ShortSnackbar(llBaseMain, "请至少选择一张图片上传", 0).show();
            //无图上传
            http();
            return;
        }

        //做压缩处理
        List<File> files = new ArrayList<>();
        for (int i = 0; i < mPicPaths.size(); i++) {
            File file = new File(mPicPaths.get(i));
            files.add(file);
        }

        UIHelper.showDialog(this, "上传中...");

        //使用Luban做压缩图片处理
        Luban.compress(this, files).setMaxSize(150).setMaxHeight(1280).setMaxWidth(720).putGear(Luban.CUSTOM_GEAR).launch(new OnMultiCompressListener() {

            @Override
            public void onStart() {
                //压缩开始
            }

            @Override
            public void onSuccess(List<File> fileList) {
                //压缩成功后的回调,上传该集合的文件
                // TODO: 2018/1/18 0018 上传图片和内容给服务,成功后

                UploadHttp(files);
            }


            @Override
            public void onError(Throwable e) {
                //压缩错误
            }
        });
    }

    /**
     * 无图上传
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "20");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("title", name);
        map.put("type2", vidioType);
        map.put("url", url);
        HttpUtils.post(HttpAdress.UPLOADVIDIO, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i("test", "错误信息是:" + e.toString());
                UiUtils.Toast("服务器异常,上传失败", false);
                CustomDialogManager.dissmiss();
            }

            @Override
            public void onResponse(String response, int id) {
                UIHelper.dismissDialog();
                UiUtils.Toast("上传成功", false);
                finish();
            }
        });
    }

    /**
     * 上传至服务器
     */
    private void UploadHttp(List<File> fileList) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "13");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("title", name);
        map.put("type2", vidioType);
        map.put("url", url);

        Map<String, File> fileMap = new HashMap<>();
        for (int i = 0; i < fileList.size(); i++) {
            fileMap.put(System.currentTimeMillis() + i + i + ".jpg", fileList.get(i));
        }

        OkHttpUtils.post().url(HttpAdress.UPLOADVIDIO).params(map).files("picture", fileMap).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i("test", "错误信息是:" + e.toString());
                UiUtils.Toast("服务器异常,上传失败", false);
                CustomDialogManager.dissmiss();
            }

            @Override
            public void onResponse(String response, int id) {
                UIHelper.dismissDialog();
                UiUtils.Toast("上传成功", false);
                finish();
            }
        });
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
        Object itemAdapter = parent.getAdapter();
        if (itemAdapter instanceof UploadShowPicGvAdapter) {
            if (mPicPaths.size() != 1) {
                if (position == ((UploadShowPicGvAdapter) itemAdapter).getCount() - 1) {
                    PickChooseManager.startPhotoPickActivity(TeacherUploadVidioActivity.this, 1 - mPicPaths.size());
                } else {
                    PickChooseManager.startShowBigActivity(TeacherUploadVidioActivity.this, mPicPaths, position);
                }
            } else {
                PickChooseManager.startShowBigActivity(TeacherUploadVidioActivity.this, mPicPaths, position);
            }
        }
    }

    /**
     * 请求图库后的回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);

                for (int i = 0; i < photos.size(); i++) {
                    mPicPaths.add(photos.get(i));
                }
                //通知适配器刷新
                adapter.notifyDataSetChanged();
            }
        }
    }


    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.iv_conmit) {
            //提交
            doUploading();
        } else if (id == R.id.iv_pingke || id == R.id.tv_pingke) {
            //评课
            vidioType = "1";
            iv_pingke.setImageResource(R.drawable.teacher_show_sel);
            iv_shaike.setImageResource(R.drawable.teacher_show_nor);
        } else if (id == R.id.iv_shaike || id == R.id.tv_shaike) {
            //晒课
            vidioType = "0";
            iv_shaike.setImageResource(R.drawable.teacher_show_sel);
            iv_pingke.setImageResource(R.drawable.teacher_show_nor);
        }
    }
}
